package cn.duyo.spring.beans.factory.support;

import cn.duyo.spring.beans.BeansException;
import cn.duyo.spring.beans.factory.FactoryBean;
import cn.duyo.spring.beans.factory.config.BeanDefinition;
import cn.duyo.spring.beans.factory.config.BeanPostProcessor;
import cn.duyo.spring.beans.factory.config.ConfigurableBeanFactory;
import cn.duyo.spring.core.convert.ConversionService;
import cn.duyo.spring.util.ClassUtils;
import cn.duyo.spring.util.StringValueResolver;

import java.util.ArrayList;
import java.util.List;

/**
 * 抽象类工厂模板
 * tips: 注意继承了单例注册器，使用的继承而非组合。这里需要处理 FactoryBean 的情况，所以将继承的 DefaultSingletonBeanRegistry 变更为 FactoryBeanRegistrySupport
 *       类似 "一个链条服务上，截出一个段来处理额外的服务，并把链条再链接上"
 * @author du
 */
@SuppressWarnings({"unchecked"})
public abstract class AbstractBeanFactory extends /*DefaultSingletonBeanRegistry ——> */ FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    /** ClassLoader to resolve bean class names with, if necessary */
    private final ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

    /** BeanPostProcessors to apply in createBean */
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    /**
     * String resolvers to apply e.g. to annotation attribute values
     */
    private final List<StringValueResolver> embeddedValueResolvers = new ArrayList<>();

    private ConversionService conversionService;

    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }

    @Override
    public boolean containsBean(String name) {
        return containsBeanDefinition(name);
    }

    protected abstract boolean containsBeanDefinition(String beanName);

    protected <T> T doGetBean(final String name, final Object[] args) {

        // 1.如果找到缓存的单例bean, 则直接返回（先找 DefaultSingletonBeanRegistry#getSingleton）
        Object sharedInstance = getSingleton(name);

        if(null != sharedInstance) {
            // 如果是 FactoryBean，则需要调用 FactoryBean#getObject
            //return (T) sharedInstance;
            return (T) getObjectForBeanInstance(sharedInstance, name);
        }

        // 2.没找到则需要根据BeanDefinition来实例化
        BeanDefinition beanDefinition = getBeanDefinition(name);
        //return (T) createBean(name, beanDefinition, args);
        Object bean = createBean(name, beanDefinition, args);
        return (T) getObjectForBeanInstance(bean, name);
    }

    private Object getObjectForBeanInstance(Object beanInstance, String beanName) {
        // 非工厂bean说明是普通bean，直接返回
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        // 从工厂bean容器缓存里获取，没有则直接调用 FactoryBeam#getObject 获取工厂bean实例，同时注册到容器缓存
        Object object = getCachedObjectForFactoryBean(beanName);

        if (object == null) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }

        return object;
    }

    /**
     * 模板方法1: 找到 BeanDefinition
     * @param beanName
     * @return
     */
    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    /**
     * 模板方法2 根据 BeanDefinition 创建bean实例
     * @param beanName
     * @param beanDefinition
     * @return
     * @throws BeansException
     */
    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor){
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    @Override
    public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
        this.embeddedValueResolvers.add(valueResolver);
    }

    @Override
    public String resolveEmbeddedValue(String value) {
        String result = value;
        for (StringValueResolver resolver : this.embeddedValueResolvers) {
            result = resolver.resolveStringValue(result);
        }
        return result;
    }

    @Override
    public void setConversionService(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    @Override
    public ConversionService getConversionService() {
        return conversionService;
    }


    /**
     * Return the list of BeanPostProcessors that will get applied
     * to beans created with this factory.
     */
    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }

    public ClassLoader getBeanClassLoader() {
        return this.beanClassLoader;
    }
}
